package com.cn.wanxi.service.impl;

import com.cn.wanxi.dao.CompanyDao;
import com.cn.wanxi.dao.impl.CompanyImpl;
import com.cn.wanxi.model.CompanyModel;
import com.cn.wanxi.service.ICompanyService;
import redis.clients.jedis.Jedis;

import java.util.ArrayList;

public class CompanyServiceImpl implements ICompanyService {
    @Override
    public CompanyModel getCompanyModel() {

        /**
         * 所有的数据全部来自于数据库
         * 1.第一次 全部来自于数据库
         * 2.第二次以后
         *  判断查询缓存里面是否有数据
         *  1）如果有，则取缓存数据
         *  2）如果没有，则取数据库
         *  然后，将数据库的数据存入缓存
         * 3.如果管理员修改了我们的公司信息，则手动清除缓存数据
         */
        final CompanyModel[] companyModel = new CompanyModel[1];

        for (int i = 0; i < 1000; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    companyModel[0] = getCompanyModelTread();
                }
            }).start();
        }
        return companyModel[0];
    }

    private synchronized CompanyModel getCompanyModelTread() {
        CompanyModel companyModel = null;
        Jedis jedis = new Jedis();
        if (jedis.exists("companyId")) {
//缓存
            companyModel = new CompanyModel();
            companyModel.setLogo(jedis.get("logo"));
            companyModel.setPhone(jedis.get("phone"));
            companyModel.setAd(jedis.get("ad"));
            companyModel.setNet(jedis.get("net"));
            companyModel.setEmail(jedis.get("email"));
            companyModel.setLinePhone(jedis.get("linePhone"));
            companyModel.setVersion(jedis.get("version"));
            companyModel.setAddress(jedis.get("address"));
            System.out.println("huancun");
        } else {
//            数据库
            CompanyDao companyDao = new CompanyImpl();
            companyModel = companyDao.getCompanyModelForFront();
//            jedis.set("companyId", companyModel.getId().toString());
            jedis.setex("companyId", 60 * 30, companyModel.getId().toString());
//            jedis.expire("companyId", 30 * 60);//自动跟新
            jedis.set("logo", companyModel.getLogo());
            jedis.set("phone", companyModel.getPhone());
            jedis.set("ad", companyModel.getAd());
            jedis.set("net", companyModel.getNet());
            jedis.set("linePhone", companyModel.getLinePhone());
            jedis.set("email", companyModel.getEmail());
            jedis.set("address", companyModel.getAddress());
            jedis.set("version", companyModel.getVersion());
            System.out.println("mysql");
        }
        return companyModel;
    }

    @Override
    public int update(CompanyModel companyModel) {
        CompanyDao companyDao = new CompanyImpl();
        int count = companyDao.update(companyModel);
        if (count == 1) {
            Jedis jedis = new Jedis();
            jedis.del("companyId");//手动更新
        }
        return count;
    }
}
